<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\SubSettlement;
use App\Models\LandingCompany;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DataCenterController extends Controller
{
    /**
     * 按落地公司统计结算数据
     */
    public function settlementByCompany(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            // 验证请求参数
            $request->validate([
                'start_date' => 'required|date',
                'end_date' => 'required|date|after_or_equal:start_date',
                'landing_company_id' => 'nullable|exists:landing_companies,id',
                'page' => 'nullable|integer|min:1',
                'per_page' => 'nullable|integer|min:1|max:100'
            ]);
            
            // 获取分页参数
            $page = (int) $request->input('page', 1);
            $perPage = (int) $request->input('per_page', 15);
            
            // 构建查询
            $query = SubSettlement::select([
                DB::raw('DATE(created_at) as date'),
                'settlements.landing_company as landing_company_name',
                'settlements.landing_company_id',
                DB::raw('COUNT(CASE WHEN sub_settlements.status = "completed" THEN 1 END) as success_count'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.pre_settlement_amount ELSE 0 END) as total_amount'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.commission ELSE 0 END) as total_commission'),
                DB::raw('AVG(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.service_fee_rate ELSE NULL END) as avg_fee_rate'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.service_fee ELSE 0 END) as total_service_fee'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "refunded" THEN sub_settlements.pre_settlement_amount ELSE 0 END) as refund_amount')
            ])
            ->leftJoin('settlements', 'sub_settlements.settlement_id', '=', 'settlements.id')
            ->where('sub_settlements.tenant_id', $tenantId)
            ->whereBetween('sub_settlements.created_at', [
                Carbon::parse($request->start_date)->startOfDay(),
                Carbon::parse($request->end_date)->endOfDay()
            ])
            ->groupBy('date', 'settlements.landing_company_id', 'settlements.landing_company')
            ->orderBy('date', 'desc');
            
            // 按落地公司过滤
            if ($request->filled('landing_company_id')) {
                $query->where('settlements.landing_company_id', $request->landing_company_id);
            }
            
            // 执行分页查询
            $result = $query->paginate($perPage, ['*'], 'page', $page);
            
            // 格式化数据
            $formattedData = $result->getCollection()->map(function ($item) {
                return [
                    'date' => $item->date,
                    'landing_company' => $item->landing_company_name ?: '未指定',
                    'landing_company_id' => $item->landing_company_id,
                    'success_count' => (int) $item->success_count,
                    'total_amount' => number_format($item->total_amount ?: 0, 2, '.', ''),
                    'total_commission' => number_format($item->total_commission ?: 0, 2, '.', ''),
                    'avg_fee_rate' => $item->avg_fee_rate ? number_format($item->avg_fee_rate * 100, 2, '.', '') . '%' : '0.00%',
                    'total_service_fee' => number_format($item->total_service_fee ?: 0, 2, '.', ''),
                    'refund_amount' => number_format($item->refund_amount ?: 0, 2, '.', '')
                ];
            });
            
            // 构建分页响应
            $paginatedResponse = [
                'data' => $formattedData,
                'current_page' => $result->currentPage(),
                'per_page' => $result->perPage(),
                'total' => $result->total(),
                'last_page' => $result->lastPage(),
                'from' => $result->firstItem(),
                'to' => $result->lastItem(),
                'first_page_url' => $result->url(1),
                'last_page_url' => $result->url($result->lastPage()),
                'next_page_url' => $result->nextPageUrl(),
                'prev_page_url' => $result->previousPageUrl(),
                'path' => $result->path(),
                'links' => $result->linkCollection()->toArray()
            ];
            
            return response()->json([
                'code' => 0,
                'message' => '获取落地公司统计数据成功',
                'data' => $paginatedResponse
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取统计数据失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 按自由职业者统计结算数据
     */
    public function settlementByFreelancer(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            // 验证请求参数
            $request->validate([
                'start_date' => 'required|date',
                'end_date' => 'required|date|after_or_equal:start_date',
                'freelancer_name' => 'nullable|string|max:100',
                'freelancer_phone' => 'nullable|string|max:20',
                'freelancer_id_card' => 'nullable|string|max:18',
                'landing_company_id' => 'nullable|exists:landing_companies,id',
                'page' => 'nullable|integer|min:1',
                'per_page' => 'nullable|integer|min:1|max:100'
            ]);
            
            // 获取分页参数
            $page = (int) $request->input('page', 1);
            $perPage = (int) $request->input('per_page', 15);
            
            // 构建查询
            $query = SubSettlement::select([
                DB::raw('DATE(sub_settlements.created_at) as date'),
                'sub_settlements.freelancer_name',
                'sub_settlements.freelancer_phone',
                'sub_settlements.freelancer_id_card',
                'settlements.landing_company as landing_company_name',
                DB::raw('COUNT(CASE WHEN sub_settlements.status = "completed" THEN 1 END) as success_count'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.pre_settlement_amount ELSE 0 END) as total_amount'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.commission ELSE 0 END) as total_commission'),
                DB::raw('AVG(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.service_fee_rate ELSE NULL END) as avg_fee_rate'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "completed" THEN sub_settlements.service_fee ELSE 0 END) as total_service_fee'),
                DB::raw('SUM(CASE WHEN sub_settlements.status = "refunded" THEN sub_settlements.pre_settlement_amount ELSE 0 END) as refund_amount')
            ])
            ->leftJoin('settlements', 'sub_settlements.settlement_id', '=', 'settlements.id')
            ->where('sub_settlements.tenant_id', $tenantId)
            ->whereBetween('sub_settlements.created_at', [
                Carbon::parse($request->start_date)->startOfDay(),
                Carbon::parse($request->end_date)->endOfDay()
            ])
            ->groupBy(
                'date', 
                'sub_settlements.freelancer_name', 
                'sub_settlements.freelancer_phone', 
                'sub_settlements.freelancer_id_card',
                'settlements.landing_company'
            )
            ->orderBy('date', 'desc');
            
            // 搜索条件
            if ($request->filled('freelancer_name')) {
                $query->where('sub_settlements.freelancer_name', 'like', '%' . $request->freelancer_name . '%');
            }
            
            if ($request->filled('freelancer_phone')) {
                $query->where('sub_settlements.freelancer_phone', 'like', '%' . $request->freelancer_phone . '%');
            }
            
            if ($request->filled('freelancer_id_card')) {
                $query->where('sub_settlements.freelancer_id_card', 'like', '%' . $request->freelancer_id_card . '%');
            }
            
            if ($request->filled('landing_company_id')) {
                $query->where('settlements.landing_company_id', $request->landing_company_id);
            }
            
            // 执行分页查询
            $result = $query->paginate($perPage, ['*'], 'page', $page);
            
            // 格式化数据
            $formattedData = $result->getCollection()->map(function ($item) {
                return [
                    'date' => $item->date,
                    'freelancer_name' => $item->freelancer_name ?: '-',
                    'freelancer_phone' => $item->freelancer_phone ?: '-',
                    'freelancer_id_card' => $item->freelancer_id_card ? 
                        substr($item->freelancer_id_card, 0, 6) . '****' . substr($item->freelancer_id_card, -4) : '-',
                    'success_count' => (int) $item->success_count,
                    'total_amount' => number_format($item->total_amount ?: 0, 2, '.', ''),
                    'total_commission' => number_format($item->total_commission ?: 0, 2, '.', ''),
                    'avg_fee_rate' => $item->avg_fee_rate ? number_format($item->avg_fee_rate * 100, 2, '.', '') . '%' : '0.00%',
                    'total_service_fee' => number_format($item->total_service_fee ?: 0, 2, '.', ''),
                    'refund_amount' => number_format($item->refund_amount ?: 0, 2, '.', '')
                ];
            });
            
            // 构建分页响应
            $paginatedResponse = [
                'data' => $formattedData,
                'current_page' => $result->currentPage(),
                'per_page' => $result->perPage(),
                'total' => $result->total(),
                'last_page' => $result->lastPage(),
                'from' => $result->firstItem(),
                'to' => $result->lastItem(),
                'first_page_url' => $result->url(1),
                'last_page_url' => $result->url($result->lastPage()),
                'next_page_url' => $result->nextPageUrl(),
                'prev_page_url' => $result->previousPageUrl(),
                'path' => $result->path(),
                'links' => $result->linkCollection()->toArray()
            ];
            
            return response()->json([
                'code' => 0,
                'message' => '获取自由职业者统计数据成功',
                'data' => $paginatedResponse
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取统计数据失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 导出落地公司统计数据
     */
    public function exportCompanyData(Request $request): JsonResponse
    {
        try {
            // 验证请求参数
            $request->validate([
                'start_date' => 'required|date',
                'end_date' => 'required|date|after_or_equal:start_date',
                'landing_company_id' => 'nullable|exists:landing_companies,id'
            ]);
            
            // 这里应该实现CSV导出逻辑
            // 暂时返回占位响应
            return response()->json([
                'code' => 0,
                'message' => '导出功能开发中...',
                'data' => [
                    'export_url' => null,
                    'filename' => '落地公司统计_' . date('Y-m-d_H-i-s') . '.csv'
                ]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '导出失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 导出自由职业者统计数据
     */
    public function exportFreelancerData(Request $request): JsonResponse
    {
        try {
            // 验证请求参数
            $request->validate([
                'start_date' => 'required|date',
                'end_date' => 'required|date|after_or_equal:start_date',
                'freelancer_name' => 'nullable|string|max:100',
                'freelancer_phone' => 'nullable|string|max:20',
                'freelancer_id_card' => 'nullable|string|max:18',
                'landing_company_id' => 'nullable|exists:landing_companies,id'
            ]);
            
            // 这里应该实现CSV导出逻辑
            // 暂时返回占位响应
            return response()->json([
                'code' => 0,
                'message' => '导出功能开发中...',
                'data' => [
                    'export_url' => null,
                    'filename' => '自由职业者统计_' . date('Y-m-d_H-i-s') . '.csv'
                ]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '导出失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
}